#######################################################
# Example of PingPong Game using FRTDEVS players
# Author: moonho.hwang@gmail.com
#   Date: Oct.19.2011
#######################################################
from XSY.DEVS.FRTDEVS import *
from XSY.DEVS.CoupledDEVS import *
from XSY.DEVS.SimEngine import SimEngine
from XSY.DEVS.VeriEngine import VeriEngine

class Player(FRTDEVS):
   ''' a ping-pong player model of FRTDEVS'''
   def __init__(m, n, iv, tl, tu, parent=None):
      '''constructor'''
      FRTDEVS.__init__(m, n, parent) 
      m.iv = iv
      m.tl, m.tu = tl, tu

      m.addInputPorts('?r')
      m.addOutputPorts('!s')

   def delta_0(m):
      '''initial state'''
      m.phase = m.iv # m.iv is the given inital state

   def rv_tau(m):
      '''lifespan range function'''
      if m.phase == 'S':
         return TInterval(m.tl,m.tu) # 
      else:
         return float('inf') # 

   def delta_x(m, x):
      '''external transition function'''
      if x.port == m.IP['?r'] and m.phase == 'W':
	 m.phase = 'S'
         return True
      else:
         return False
               
   def delta_y(m):
      '''output and internal transition function'''
      if m.phase == 'S':
	 m.phase = 'W'
         y = PortValue(m.OP["!s"])
         return y
   
   def get_state(m):
      '''get the state'''
      return m.phase

   def set_state(m, s):
      '''set the state as s'''
      m.phase = s
 
def makeModel():
   '''make player'''
   return  Player('A', 'W', .10, .20)

def inject_CB(md):
   '''inject CB'''
   return md, PortValue(md.IP['?r'])

def runSimulation(md):
   engine = SimEngine(md, inject_CB)
   engine.runInteractiveMenu()
############################################################################################################

if __name__ == '__main__':
   md = makeModel()
   runSimulation(md)
   print "good bye~!" 
